package netWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: UDP回显服务器练习
 * User: 王圆豪
 * Date: 2025-05-15
 * Time: 16:45
 */
public class UdpEchoClient1 {
    private DatagramSocket socket = null;

    private String serverIP;

    private int serverPort;

    public UdpEchoClient1(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        //不传入固定端口号，防止冲突
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端开启！");
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入你要发送的内容：");
            String request = sc.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    0,request.getBytes().length, InetAddress.getByName(serverIP)
                    ,serverPort);
            socket.send(requestPacket);

            DatagramPacket reponsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(reponsePacket);
            String reponse = new String(reponsePacket.getData(),0,reponsePacket.getLength());
            System.out.println(reponse);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient1 client1 = new UdpEchoClient1("127.1.1.0",9090);
        client1.start();
    }
}
